package com.zrh.pma.pma.controllers;

import com.zrh.pma.pma.entities.Student;
import com.zrh.pma.pma.services.StudentSeivice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


@Controller
@RequestMapping("students")
public class StudentControlle {
    @Autowired
    StudentSeivice studentSeivice;
    @GetMapping
    public String displayStudents(Model model){
        List<Student> students = studentSeivice.getAll();
        model.addAttribute("students",students);
        return "students/list-students";
    }
    @GetMapping("/new")
    public String displayStudentForm(Model model) {
        Student aStudent = new Student();
        model.addAttribute("student", aStudent);
        return "students/new-student";
    }

    @PostMapping("/save")
    public String createStudent(Model model, @Valid Student student, Errors errors) {
        if(errors.hasErrors())
            return "students/new-student";
        studentSeivice.save(student);
        return "redirect:/students";

    }
    @GetMapping("/update")
    public String displayStudentUpdateForm(@RequestParam("id")long theId,Model model){

        Student theStudent=studentSeivice.findByStudentId(theId);
        model.addAttribute("student",theStudent);
        return "students/new-student";
    }
    @GetMapping("/delete")
    public String displayStudentDeleteForm(@RequestParam("id")long theId,Model model){
        Student theStudent = studentSeivice.findByStudentId(theId);
        studentSeivice.delete(theStudent);
        model.addAttribute("student",theStudent);
        return "students/list-students";
    }

}